<?php

namespace app\models;

use Yii;
use yii\web\Link; // represents a link object as defined in JSON Hypermedia API Language.
use yii\web\Linkable;
use yii\helpers\Url;

/**
 * This is the model class for table "country".
 *
 * @property string $code
 * @property string $name
 * @property int $population
 */
class Country extends \yii\db\ActiveRecord implements Linkable
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'country';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['code', 'name'], 'required'],
            [['population'], 'integer'],
            [['code'], 'string', 'max' => 2],
            [['name'], 'string', 'max' => 52],
            [['code'], 'unique'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'code' => 'Code',
            'name' => 'Name',
            'population' => 'Population',
        ];
    }

    public function fields()
    {
        return [
            // 字段名和属性名相同
            'code',
            // 字段名为"email", 对应的属性名为"email_address"
            'email' => 'population',
            // 字段名为"name", 值由一个PHP回调函数定义
            'name' => function ($model) {
                return $model->name . ' ' . $model->code;
            },
        ];
    }

    public function extraFields()
    {
        return ['profile'];
    }

    public function getLinks()
    {
        return [
            Link::REL_SELF => Url::to(['user/view', 'id' => $this->code], true),
            'edit' => Url::to(['user/view', 'id' => $this->code], true),
            'profile' => Url::to(['user/profile/view', 'id' => $this->code], true),
            'index' => Url::to(['users'], true),
        ];
    }
}
